package xyz.zchao.blog.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import xyz.zchao.blog.annotation.IgnoreToken;
import xyz.zchao.blog.pojo.Tag;
import xyz.zchao.blog.service.TagService;
import xyz.zchao.blog.util.PageResultVO;
import xyz.zchao.blog.util.ResultCode;
import xyz.zchao.blog.util.ResultVO;

import javax.validation.Valid;
import java.util.List;

/**
 * @Description:
 * @Author: guozongchao
 * @Date: 2020/5/16 17:40
 */
@RestController
@RequestMapping("/tag")
public class TagController {

    @Autowired
    private TagService tagService;

    @IgnoreToken
    @GetMapping("/list")
    public PageResultVO getTags(@RequestParam(required = false) Integer page, @RequestParam(required = false) Integer limit) {
        List<Tag> tags = tagService.retrieveAllByPaging(page, limit);
        long count = tagService.getCount();
        return new PageResultVO(ResultCode.SUCCESS, tags, count);
    }

    @IgnoreToken
    @GetMapping("/list/{tid}")
    public ResultVO getTag(@PathVariable("tid") Integer tid) {
        Tag tag = tagService.retrieveById(tid);
        return new ResultVO(ResultCode.SUCCESS, tag);
    }

    @PutMapping("/list/{tid}")
    public ResultVO updateTag(@PathVariable("tid") Integer tid, @RequestBody @Valid Tag record) {
        record.setTagId(tid);
        tagService.update(record);
        return new ResultVO(ResultCode.SUCCESS, null);
    }

    @DeleteMapping("/list/{tid}")
    public ResultVO deleteTag(@PathVariable("tid") Integer tid) {
        tagService.deleteById(tid);
        return new ResultVO(ResultCode.SUCCESS, null);
    }

    @PostMapping("/add")
    public ResultVO addTags(@RequestBody @Valid Tag record) {
        tagService.create(record);
        return new ResultVO(ResultCode.SUCCESS, null);
    }

    @IgnoreToken
    @GetMapping("/search")
    public ResultVO searchTags(@RequestParam String keyword) {
        List<Tag> tags = tagService.findTagsByName(keyword);
        return new ResultVO(ResultCode.SUCCESS, tags);
    }
}
